class FirstPage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            thumburl: '',
            name: '',
            id: '0',
            partcount: 1,
            parts: [{ src: '' }, { src: '' }, { src: '' }],
            categorylist: [],
            swiperimg: [],
            swiperimglist: [],
            category_select_list: [],
            recommendtablehtml: [],
            recommendlist: [],
            goods_select_html: [],
        };
    }




    componentDidMount() {
        $(`#goodsType0`).attr("checked", true);
        //this.freshlist();
        var { cids, goods_select_html } = this.state, that = this;

        getlist(listres => {
            if (listres.issuccess == 1) {

                this.setState({ goodslist: listres.list })
                getmain(res => {

                    if (res.issuccess == 1) {
                        let parts = JSON.parse(HtmlUtil.htmlDecodeByRegExp(res.parts)),
                            swiperimglist = JSON.parse(HtmlUtil.htmlDecodeByRegExp(res.swiper)),
                            partcount = parts.length,

                            swiperimg = [];

                        //轮播图
                        if (swiperimglist.length > 0) {
                            swiperimglist.forEach((x, i) => {
                                swiperimg.push(
                                    <div className={"detailimg_div index" + i} key={i}>
                                        <img key={i} src={`${API_HEAD}imgs/${x}`} className="img-responsive" />
                                        <img key={"close_" + i} className='closeimg' onClick={that.del_swiper_img.bind(that, i)} src='./src/img_close.png' />
                                    </div>
                                )
                            })
                            //专区
                            parts.map((x, i) => {
                                if (x.src == '') {
                                    partcount--
                                }
                            })
                            for (let index = 0; index < partcount; index++) {
                                let ids = parts[index]['ids'] || '', arr = [], img = parts[index]['src'];
                                parts[index]['src'] = `${API_HEAD}imgs/${parts[index]['src']}`


                                if (ids.indexOf(',') > -1) {
                                    arr = ids.split(',');
                                } else {
                                    arr = [ids];
                                }
                                console.log(arr, 'arr');

                                // console.log(parts[index].ids.split(','),'parts[index].ids');

                                // console.log(parts[index].ids,'parts');

                                if (arr.length > 0) {
                                    arr.forEach(x => {
                                        this.formatgoodslist(listres.list, [], index, x)
                                    })
                                }

                            }

                            that.setState({
                                swiperimg,
                                swiperimglist,
                                partcount,
                                parts,
                                finishupload: !0,
                            })
                        }
                        console.log(parts, 'parts');

                        // var partcount = 0;


                        // parts.forEach(x => {
                        //     if (x.name.length > 0) partcount++;
                        // });
                        // var recommendlist = res.recommend.split(',');
                        // getlist(res => {
                        //     if (res.issuccess == 1) {
                        //         var list = res.list, recommend_select_html = [], recommendtablehtml = [];
                        //         list.forEach((x, i) => {
                        //             recommendlist.forEach((y, j) => {
                        //                 if (y == x.id) {
                        //                     recommendtablehtml.push(
                        //                         <tr key={j}>
                        //                             <td>{x.name}</td>
                        //                             <td>{x.describe}</td>
                        //                             <td className='operate'>
                        //                                 <p className='edit' onClick={this.edit.bind(this, x.id)}>编辑</p>
                        //                                 <p onClick={this.del.bind(this, x.id)}>删除</p>
                        //                             </td></tr>
                        //                     )
                        //                 }
                        //             });


                        //             recommend_select_html.push(
                        //                 <option key={i} value={x.id}>{x.name}   {x.describe}
                        //                 </option>
                        //             )
                        //         })

                        //     }

                        //     this.setState({ parts, recommendtablehtml, partcount, finishupload: !0, recommend_select_html, goodslist: list, goodsid: list[0]['id'], recommendlist })
                        // })
                    }

                })




            }
        })


        // getcategorylist(res => {
        //     res.list.forEach((x, i) => {
        //         goods_select_html.push(
        //             <option key={i} value={x.id}>{x.name}
        //             </option>
        //         )
        //     })
        //     this.setState({ goods_select_html, categorylist: res.list });
        // });






    }

    filechange(e) {
        console.log('filechange');

        this.setState({
            finishupload: !1,
            uploadword: "上传"
        })
        var that = this;
        var filedata = $('#file3')[0].files[0];

        var reader = new FileReader();
        reader.readAsDataURL(filedata);
        reader.onload = function (e) {
            var base64str = e.target.result;
            that.putlistdata([base64str])
        }
    }

    del_swiper_img(e) {
        var that = this;
        var swiperimg = [];
        var swiperimglist = this.state.swiperimglist;
        swiperimglist.splice(e, 1);
        swiperimglist.forEach((x, i) => {
            swiperimg.push(
                <div className={"detailimg_div index" + i} key={i}>
                    <img key={i} src={x} className="img-responsive" />
                    <img key={"close_" + i} className='closeimg' onClick={that.del_swiper_img.bind(that, i)} src='./src/img_close.png' />
                </div>
            )
        })
        that.setState({
            swiperimg,
            swiperimglist,

        })

    }

    putlistdata(target) {
        console.log('putlistdata');
        var that = this;
        target.forEach((x, i) => {

            var base64prop = 'swiperimglist'
                , prop = 'swiperimg'
                , list = that.state[prop]
                , src = x
                , onclicktap = that.del_swiper_img.bind(that, list.length);
            if (!isBase64(src)) {
                if (src.indexOf(`${API_HEAD}`) == -1) {
                    src = `${API_HEAD}imgs/${src}`
                }
            }
            var base64list = that.state[base64prop] || [];
            base64list.push(src);
            list.push(
                <div className={prop + "_div index" + list.length} key={list.length}>
                    <img key={list.length} src={src} className="img-responsive" />
                    <img key={"close_" + list.length} className='closeimg' onClick={onclicktap} src='./src/img_close.png' />
                </div>
            )
            that.setState({
                [base64prop]: base64list,
                [prop]: list
            })
            console.log(list, 'listlistlist');


        });

    }



    inputchange(i, e) {
        var parts = this.state.parts;
        parts[i]['name'] = e.target.value
        this.setState({ parts })
    }
    clickupload(e) {
        console.log('clickupload', e);
        $('#file' + e).click();
    }
    del_detail_img(e) {
        var parts = this.state.parts;
        parts[e]['src'] = '';
        this.setState({ finishupload: !1, parts });
    }

    getbase64url(index) {
        var that = this;
        var reader = new FileReader();
        reader.readAsDataURL($('#file' + index)[0].files[0]);
        reader.onload = function (e) {
            var thumburl = e.target.result;
            var parts = that.state.parts;
            parts[index]['src'] = thumburl;
            that.setState({ parts })

            //  that.putlistdata(filecode,[base64str])
        }
    }

    filechange0(e) {
        var that = this;
        this.setState({
            finishupload: !1,
            uploadword: "上传"
        })
        this.getbase64url(0)

    }
    filechange1(e) {
        var that = this;
        this.setState({
            finishupload: !1,
            uploadword: "上传"
        })
        this.getbase64url(1)

    }
    filechange2(e) {
        var that = this;
        this.setState({
            finishupload: !1,
            uploadword: "上传"
        })
        this.getbase64url(2)
    }



    //下载所有base64的图片并进行保存
    upload() {
        var { partcount, parts, swiperimglist } = this.state, err = '', newswiperist = [], that = this;
        for (let index = 0; index < partcount; index++) {
            var src = parts[index]['src'];
            if (isBase64(src)) {
                uploadimg(src, res => {
                    if (res.issuccess == 1) {
                        parts[index]['src'] = `${API_HEAD}imgs/${res.path}`

                    } else {
                        alert(res.msg)
                        err = 1
                        return;
                    }
                })
            }
        }

        swiperimglist.forEach(x => {
            if (isBase64(x)) {
                uploadimg(x, res => {
                    if (res.issuccess == 1) {
                        newswiperist.push(res.path)//`${API_HEAD}imgs/${res.path}`)
                    } else {
                        alert(res.msg)
                        err = 1
                        return;
                    }
                })
            } else {
                newswiperist.push(x)
            }
        })
        this.setState({ swiperimglist: newswiperist })

        if (err == '') {
            this.setState({
                finishupload: !0,
                parts
            })
        }
    }

    edit(e) {
        console.log('edit', e);
        window.location.href = './goods.html?id=' + e

    }

    onrecommendchange(i, e) {
        let prop = `goodsid${i}`
        console.log(i, 'iii');
        console.log(prop, 'prop');

        this.setState({ [prop]: e.target.value, })
    }
    oncategorychange(i, x) {
        var { parts } = this.state;
        parts[i]['cid'] = Number(x.target.value)
        this.setState({ parts })
    }

    addpart() {
        var partcount = this.state.partcount + 1;
        this.setState({ partcount });
        // let {parthtml} = this.state,count = parthtml.coun;
        // newparthtml.push(
        //     <div className='module_part'>
        //     <div className="input-group">
        //         <span className="input-group-addon">专区名称</span>
        //         <input id='name' onChange={this.inputchange.bind(this, 0)} value={parts[0]['name']} type="text" placeholder='请输入专区名称' className="form-control" />
        //     </div>
        //     <div className="input-group input-group ">
        //         <span className="input-group-addon desc">海报</span>
        //         <input onChange={this.filechange0.bind(this)} type='file' id='file0' />
        //         <div className='img_warp' >
        //             <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, 0)} style={{ display: parts[0]['src'].length > 0 ? "none" : "" }} />
        //             <img style={{ display: parts[0]['src'].length > 0 ? "block" : "none" }} src={parts[0]['src']} className="img-responsive" />
        //             <img className='closeimg thumb' style={{ display: parts[0]['src'].length > 0 ? "block" : "none" }} onClick={this.del_detail_img.bind(this, 0)} src='./src/img_close.png' />
        //         </div>
        //     </div>

        //     <div className="input-group">
        //         <span className="input-group-addon">商品类型</span>
        //         <select value={parts[0]['cid']} onChange={this.oncategorychange.bind(this, 0)} className="form-control select">
        //             {this.state.category_select_html}
        //         </select>
        //     </div>
        //     </div>

        // )

    }

    save() {
        var { partcount, parts, finishupload, categorylist, swiperimglist } = this.state, part = [];
        // console.log(parts, 'parts');
        console.log(swiperimglist, 'swiperimglist');

        for (let index = 0; index < partcount; index++) {
            let ids = this.state['checklist' + index] || '', item = parts[index];
            console.log(parts[index]['src'], 'parts[index][]0');
            parts[index]['src'] = parts[index]['src'].replace(`${API_HEAD}imgs/`, '');
            console.log(parts[index]['src'], 'parts[index][]1');

            if (ids == '') {
                alert('请添加商品')
                return
            }
            item['ids'] = ids.join(',');
            if (!ids) {
                alert('请添加商品')
                return;
            }
            if (item.src.length == 0) {
                alert('请添加图片');
            }
            if (item.name.length == 0) {
                alert('请填写专区名称');
            }
        }
        if (!finishupload) {
            alert('请上传图片');
            return;
        }

        if (swiperimglist.length == 0) {
            alert('请上传轮播图');
            return;
        }
        console.log(swiperimglist, 'swiperimglist');
        editmain({ parts: JSON.stringify(parts), swiper: JSON.stringify(swiperimglist) }, res => {
            if (res.issuccess == 1) {
                alert('保存成功')
            }
        })
    }
    //确定添加
    confirm_recommend(i) {
        let checklist = this.state[`checklist${i}`] || [],
            { goodslist } = this.state,
            id = this.state[`goodsid${i}`] || goodslist[0].id,
            html = this.state[`recommendtablehtml${i}`] || [];
        // recommendtablehtml0
        console.log(html, 'html');
        if (checklist.indexOf(id) > -1) {
            alert('请不要重复添加');
            return;
        }
        console.log('checklist', checklist);


        // var { recommendtablehtml, recommendlist, goodslist } = this.state, item = {};
        checklist.push(Number(id));
        this.formatgoodslist(goodslist, html, i, id)


    }

    formatgoodslist(list, html, i, id) {

        let goodsType = "";
        let that = this, checklist = this.state[`checklist${i}`] || [];
        checklist.push(id);
        $(".goodsType").each(function () {
            var isChecked = $(this).attr("checked");
            if ($(this).is(":checked")) {
                goodsType = $(this).val();

            }
        });
        if (list.length > 0) {

            if (i == 3) {
                list.forEach(x => {

                    if (x.id == id)
                        html.push(
                            <tr key={html.length}>
                                <td>{x.name}</td>
                                <td>{goodsType}</td>
                                <td className='operate'>
                                    <p onClick={that.del.bind(that, x.id)}>删除</p>
                                </td></tr>
                        )
                    this.setState({ [`recommendtablehtml${i}`]: html, [`checklist${i}`]: checklist })

                });
            } else {
                list.forEach(x => {
                    if (x.id == id)
                        html.push(
                            <tr key={html.length}>
                                <td>{x.name}</td>
                                <td>{x.describe}</td>
                                <td className='operate'>
                                    <p className='edit' onClick={that.edit.bind(that, x.id)}>编辑</p>
                                    <p onClick={that.del.bind(that, x.id)}>删除</p>
                                </td></tr>
                        )
                    this.setState({ [`recommendtablehtml${i}`]: html, [`checklist${i}`]: checklist })

                });

            }
        }


    }
    del(e) {
        var { recommendlist, recommendtablehtml } = this.state, index = -1;
        recommendlist.forEach((x, i) => {
            if (x == e) {
                var list = recommendlist;
                index = i
                list.splice(i, 1);
                recommendtablehtml.splice(i, 1);
                console.log(list, 'list')
                console.log(recommendtablehtml, 'recommendtablehtml')
                this.setState({ recommendtablehtml, recommendlist: list })
            }
        });





    }

    goodsStyle(e) {

        var goods_select_html = [];

        if (e == 1) {
            this.state.goodslist.forEach((x, i) => {
                goods_select_html.push(
                    <option key={i} value={x.id}>{x.name}
                    </option>
                )
            });

        } else {
            this.state.categorylist.forEach((x, i) => {
                goods_select_html.push(
                    <option key={i} value={x.id}>{x.name}
                    </option>
                )
            });
        }

        $(`#goodsType${e}`).attr("checked", true);

        this.setState({
            goods_select_html
        });
    }


    render() {
        var { parts } = this.state;


        return (
            <div>

                <div className='content_wrap panel-default content_wrap'>
                    <div className='breadLine '>
                        当前位置 > 首页管理
                        </div>
                    <div className='inputs panel-body'>
                        <h3>首页管理</h3>
                    </div>

                    <div className='module_part'>
                        <span className="part_title">轮播图</span>
                        <p className='notice'>*图片宽高比为2.5:1</p>
                        <div className="input-group input-group imgs">
                            <input onChange={this.filechange.bind(this)} type='file' id='file3' />
                            <div className='detail_btns'>
                                <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, 3)} />
                                <div className='img_warp' >
                                    {this.state.swiperimg}
                                </div>
                            </div>

                        </div>



                        {/* <div className="input-group">
                            <span className="input-group-addon">商品类型</span>
                            <select value={parts[0]['cid']} onChange={this.oncategorychange.bind(this, 0)} className="form-control select">
                                {this.state.category_select_html}
                            </select>
                        </div>   */}
                        <div>
                            <span style={{ marginRight: "20px" }}>
                                <input id="goodsType0" type="radio" onClick={this.goodsStyle.bind(this, 0)} name="goodsType" value="列表" className="goodsType" />列表
                            </span>
                            <input id="goodsType1" type="radio" onClick={this.goodsStyle.bind(this, 1)} name="goodsType" value="商品" className="goodsType" />商品
                            <br />
                        </div>

                        <div className="input-group">
                            <select value={this.state.goodsid0} onChange={this.onrecommendchange.bind(this, 3)} className="form-control select">
                                {this.state.goods_select_html}
                            </select>
                            <button onClick={this.confirm_recommend.bind(this, 3)} className='btn submit btn-primary center ' >确定添加</button>
                        </div>
                        <table className="table table-hover">
                            <thead>
                                <tr>
                                    <th>链接对象</th>
                                    <th>类型</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {this.state.recommendtablehtml3}
                            </tbody>
                        </table>
                    </div>
                    {/* 按钮组*/}



                    <div className='module_part'>


                        <div className="input-group">
                            <span className="input-group-addon">专区名称</span>
                            <input id='name' onChange={this.inputchange.bind(this, 0)} value={parts[0]['name']} type="text" placeholder='请输入专区名称' className="form-control" />
                        </div>
                        <div className="input-group input-group ">
                            <span className="input-group-addon desc">海报</span>
                            <input onChange={this.filechange0.bind(this)} type='file' id='file0' />
                            <div className='img_warp' >
                                <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, 0)} style={{ display: parts[0]['src'].length > 0 ? "none" : "" }} />
                                <img style={{ display: parts[0]['src'].length > 0 ? "block" : "none" }} src={parts[0]['src']} className="img-responsive" />
                                <img className='closeimg thumb' style={{ display: parts[0]['src'].length > 0 ? "block" : "none" }} onClick={this.del_detail_img.bind(this, 0)} src='./src/img_close.png' />
                            </div>
                        </div>

                        {/* <div className="input-group">
                            <span className="input-group-addon">商品类型</span>
                            <select value={parts[0]['cid']} onChange={this.oncategorychange.bind(this, 0)} className="form-control select">
                                {this.state.category_select_html}
                            </select>
                        </div> */}

                        <div className="input-group">
                            <select value={this.state.goodsid0} onChange={this.onrecommendchange.bind(this, 0)} className="form-control select">
                                {this.state.goods_select_html}
                            </select>
                            <button onClick={this.confirm_recommend.bind(this, 0)} className='btn submit btn-primary center ' >确定添加</button>
                        </div>
                        <table className="table table-hover">
                            <thead>
                                <tr>
                                    <th>商品名称</th>
                                    <th>商品描述</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                {this.state.recommendtablehtml0}
                            </tbody>
                        </table>
                    </div>


                    <div style={{ display: this.state.partcount > 1 ? '' : 'none' }} className='module_part'>
                        <div className="input-group">
                            <span className="input-group-addon">专区名称</span>
                            <input id='name' onChange={this.inputchange.bind(this, 1)} value={parts[1]['name']} type="text" placeholder='请输入专区名称' className="form-control" />
                        </div>

                        <div className="input-group input-group ">
                            <span className="input-group-addon desc">海报</span>
                            <input onChange={this.filechange1.bind(this)} type='file' id='file1' />
                            <div className='img_warp' >
                                <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, 1)} style={{ display: parts[1]['src'].length > 0 ? "none" : "" }} />
                                <img style={{ display: parts[1]['src'].length > 0 ? "block" : "none" }} src={parts[1]['src']} className="img-responsive" />
                                <img className='closeimg thumb' style={{ display: parts[1]['src'].length > 0 ? "block" : "none" }} onClick={this.del_detail_img.bind(this, 1)} src='./src/img_close.png' />
                            </div>

                            {/* <div className="input-group">
                            <span className="input-group-addon">商品类型</span>
                            <select value={parts[1]['cid']} onChange={this.oncategorychange.bind(this, 1)} className="form-control select">
                                {this.state.category_select_html}
                            </select>
                        </div> */}

                            <div className="input-group">
                                <select value={this.state.goodsid1} onChange={this.onrecommendchange.bind(this, 1)} className="form-control select">
                                    {this.state.goods_select_html}
                                </select>
                                <button onClick={this.confirm_recommend.bind(this, 1)} className='btn submit btn-primary center ' >确定添加</button>
                            </div>
                            <table className="table table-hover">
                                <thead>
                                    <tr>
                                        <th>商品名称</th>
                                        <th>商品描述</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {this.state.recommendtablehtml1}
                                </tbody>
                            </table>
                        </div>



                    </div>

                    <div style={{ display: this.state.partcount > 2 ? '' : 'none' }} className='module_part'>
                        <div className="input-group">
                            <span className="input-group-addon">专区名称</span>
                            <input id='name' onChange={this.inputchange.bind(this, 2)} value={parts[2]['name']} type="text" placeholder='请输入专区名称' className="form-control" />
                        </div>
                        <div className="input-group input-group ">
                            <span className="input-group-addon desc">海报</span>
                            <input onChange={this.filechange2.bind(this)} type='file' id='file2' />
                            <div className='img_warp' >
                                <img className='fileimg' src={Constant.UPLOADBTN} onClick={this.clickupload.bind(this, 2)} style={{ display: parts[2]['src'].length > 0 ? "none" : "" }} />
                                <img style={{ display: parts[2]['src'].length > 0 ? "block" : "none" }} src={parts[2]['src']} className="img-responsive" />
                                <img className='closeimg thumb' style={{ display: parts[2]['src'].length > 0 ? "block" : "none" }} onClick={this.del_detail_img.bind(this, 2)} src='./src/img_close.png' />
                            </div>

                            {/* <div className="input-group">
                            <span className="input-group-addon">商品类型</span>
                            <select value={parts[2]['cid']} onChange={this.oncategorychange.bind(this, 2)} className="form-control select">
                                {this.state.category_select_html}
                            </select>
                        </div> */}

                            <div className="input-group">
                                <select value={this.state.goodsid2} onChange={this.onrecommendchange.bind(this, 2)} className="form-control select">
                                    {this.state.goods_select_html}
                                </select>
                                <button onClick={this.confirm_recommend.bind(this, 2)} className='btn submit btn-primary center ' >确定添加</button>
                            </div>
                            <table className="table table-hover">
                                <thead>
                                    <tr>
                                        <th>商品名称</th>
                                        <th>商品描述</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {this.state.recommendtablehtml2}
                                </tbody>
                            </table>
                        </div>

                    </div>
                    <button style={{ display: this.state.partcount > 2 ? 'none' : '' }} onClick={this.addpart.bind(this)} className='btn addpart btn-primary center ' >添加专区</button>


                    <button style={{ marginLeft: '25vw' }} onClick={this.save.bind(this)} className='btn addpart btn-primary center w20 ' >保存</button>
                    <button onClick={this.upload.bind(this)} className={`btn addpart btn-${this.state.finishupload ? 'success' : 'primary'} center w20`} >{this.state.finishupload ? '上传成功' : '上传图片'}</button>
                </div >


            </div >
        )
    }
}





ReactDOM.render(
    <div>
        <TopLine />
        {/* <LeftMenu code='0' /> */}
        <LeftMenu code='firstPage1' />
        <FirstPage />
    </div>
    //<Barrage/>
    , $('.container')[0]
)